import { AfterViewInit, Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { CookieService } from 'ngx-cookie-service';
import { AuthService } from 'src/app/core/auth/auth.service';
import { UniversalService } from 'src/app/core/util/universal.service';
import { Router } from '@angular/router';

@Component({
    selector: 'app-login',
    templateUrl: './login.component.html',
    styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit, AfterViewInit {
    loginTitle = '跃进渠综合调度系统';
    // remember = false;
    hidePwd = true;
    validateForm: FormGroup;

    constructor(
        private fb: FormBuilder,
        private router: Router,
        private cookie: CookieService,
        private authService: AuthService,
        private universalService: UniversalService
    ) {
    }

    ngOnInit(): void {
        this.validateForm = this.fb.group({
            userName: [this.cookie.get('account') || '', [Validators.required]],
            password: [this.cookie.get('password') || '', [Validators.required]]
        });
    }

    ngAfterViewInit() {
        this.authService.logout();
    }

    submitForm(): void {
        const userName = this.validateForm.controls['userName'].value || '';
        const password = this.validateForm.controls['password'].value || '';
        this.cookie.set('account', userName);
        this.cookie.set('password', password);

        this.authService.login(userName, password).subscribe(success => {
            if (success) {
                setTimeout(() => {
                        console.log(this.universalService.getRouterHistory()[1]);
                        const url =
                            this.universalService.getRouterHistory()[1] &&
                            this.authService.menuDataChanged
                                .getValue()
                                .find((item) => {
                                    return (
                                        item.href ===
                                        this.universalService.getRouterHistory()[1]
                                    );
                                })
                                ? this.universalService.getRouterHistory()[1]
                                : '/realtime-control/dispatch-glc';
                        this.router.navigate(['portal']);
                    }
                );
            }
        });
    }
}
